<?php
/**
 * User service
 */
class Member_Service_User extends App_Service_ServiceAbstract
{
    /**
     * Datamapper used for articles
     * 
     * @var Default_Model_Mapper_UserInterface
     */
    protected $_mapper;

    /**
     * Current user
     * 
     * @var Zend_Acl_Role
     */
    protected $_currentUser;

    /**
     * Forms for this service
     *
     * @var array
     */
    protected $_forms = array();
    
    /**
     * Instantiate the service with the correct datamapper
     * 
     * @param Member_Model_Mapper_User $mapper
     */
    public function __construct()
    {
        $this->_mapper = new Member_Model_UserMapper();
    } 

    /**
     * Log in
     *
     * @param  array $data
     * @return boolean
     */
    public function login(array $data)
    {
    	//TODO : � ce stade, cette methode ne retourne rien
        $form = $this->getLoginForm();

        if (!$form->isValid($data)) {
           return false;
        }

       $this->_mapper->setIdentity($data['username'])
                      ->setCredential(sha1($data['password'] . Zend_Registry::get('config')->salt))
                      ->setIdentityColumn('username')
                      ->setCredentialColumn('password')
                      ->setLoginTableName('core_user');

        $result = $this->_mapper->authenticate();
       
        if ($data['remember'] === '1') {
            App_Cookie::setEncrypted('username', $data['username']);
            App_Cookie::setEncrypted('password', $data['password']);
        }

        return true;
    }

    /**
     * Log the current use rout
     *
     * @return void
     */
    public function logout()
    {
        Zend_Auth::getInstance()->clearIdentity();

        App_Cookie::clear('username');
        App_Cookie::clear('password');
    }
    /**
     * Fetch a user by it's ID
     *
     * @param  integer $id
     * @return Default_Model_User
     */
    public function fetchById($id)
    {
        $user = $this->_mapper->fetchById($id);

        return $user;
    }
    
    public static function getIdentity()
    {
    	return Member_Model_UserMapper::getIdentity();
    }

    /**
     * Get the login form
     *
     * @return Default_Form_UserLogin
     */
    public function getLoginForm()
    {
        if (!isset($this->_forms['login'])) {
            $this->_forms['login'] = new Member_Form_UserLogin();
        }

        return $this->_forms['login'];
    }    
}
